import java.util.Random;

public final class Code {
    private String code;
    private StringBuffer codeing;

    //加密
    public String codeEncryption() {
        codeing = new StringBuffer();
        for (int i = 0; i < code.length(); i++) {
            codeing.append(((char) (code.charAt(i) + i + 4)));
        }
        return codeing.charAt(0) + codeing.reverse().substring(1, codeing.length() - 1) + codeing.charAt(0);
    }

    //解密界面
    public String codeDecrypt() {
        codeing = new StringBuffer(code);
        code = codeing.charAt(0) + codeing.reverse().substring(1, codeing.length() - 1) + codeing.charAt(0);
        codeing = new StringBuffer();
        for (int i = 0; i < code.length(); i++) {
            codeing.append(((char) (code.charAt(i) - i - 4)));
        }
        return codeing + "";
    }

    //检查密码是否合法
    public static boolean inspectCode(String string) {
        boolean a = false;
        if (string.length() <= 16) {
            a = true;
            for (int i = 0; i < string.length(); i++) {
                char ch = string.charAt(i);
                if (ch >= 65 && ch <= 90) {

                } else if (ch >= 97 && ch <= 122) {

                } else if (ch >= 48 && ch <= 57) {

                } else {
                    a = false;
                    break;
                }
            }
        }
        return a;
    }

    //判断密码强度
    public char passwordStrength() {
        char i;
        if (code.length() < 8) {
            i = '弱';
        } else {
            int a = 0, b = 0, c = 0;
            for (int j = 0; j < code.length(); j++) {
                char s = code.charAt(j);
                if (s >= 48 && s <= 58) {
                    a++;
                } else if (s >= 65 && s <= 90) {
                    b++;
                } else if (s >= 97 && s <= 122) {
                    c++;
                }
            }
            if (a != 0 && (b + c) != 0) {
                if (b > 0 && c > 0) {
                    i = '强';
                } else {
                    i = '中';
                }
            } else {
                i = '弱';
            }
        }
        return i;
    }

    //密码生成器，在用户设定密码长度后，帮助用户随机生成强密码并显示。
    public String getCode() {
        Random random = new Random();
        codeing = new StringBuffer();
        String s="0123456789QWERTYUIOPLKJHGFDSAZXCVBNMzxcvbnmasdfghjklpoiuytrewq";
        for (int i = 0; i < random.nextInt(9) + 8; i++) {
            codeing.append(s.charAt(random.nextInt(s.length())));
        }
        setCode(codeing.toString());
        if(passwordStrength()=='强'){
            return codeing.toString();
        } else  {
            return getCode();
        }
    }

    public void setCode(String code) {
        this.code = code;
    }
}

